/**
 * 反馈回路系统 - 建立Phase间信息传递的双向验证机制
 */

export interface FeedbackLoop {
  sourcePhase: number;
  targetPhase: number;
  feedbackType: 'validation' | 'correction' | 'enhancement';
  triggers: FeedbackTrigger[];
}

export interface FeedbackTrigger {
  condition: string;
  threshold: number;
  action: FeedbackAction;
}

export interface FeedbackAction {
  type: 'rollback' | 'correct' | 'enhance' | 'alert';
  instructions: string;
  affectedPhases: number[];
}

export interface InformationTrackingRecord {
  id: string;
  sourcePhase: number;
  elementType: string;
  elementId: string;
  extractedData: any;
  transformationHistory: TransformationStep[];
  currentStatus: 'active' | 'transformed' | 'lost' | 'deprecated';
  lossReason?: string;
  impactAssessment?: 'low' | 'medium' | 'high' | 'critical';
}

export interface TransformationStep {
  fromPhase: number;
  toPhase: number;
  transformation: string;
  dataLoss: {
    lostFields: string[];
    reason: string;
    approved: boolean;
  };
  timestamp: number;
}

// 信息保真度追踪器
export class InformationFidelityTracker {
  private records: Map<string, InformationTrackingRecord> = new Map();
  private phaseOutputs: Map<number, any> = new Map();

  // 记录Phase输出
  recordPhaseOutput(phase: number, output: any): void {
    this.phaseOutputs.set(phase, output);

    if (phase === 1) {
      this.initializeFromFigmaData(output);
    } else {
      this.trackTransformation(phase - 1, phase, output);
    }
  }

  // 从Figma数据初始化信息追踪
  private initializeFromFigmaData(figmaOutput: any): void {
    const { designContext } = figmaOutput;

    designContext.forEach((node: any) => {
      const record: InformationTrackingRecord = {
        id: `figma_${node.id}`,
        sourcePhase: 1,
        elementType: node.type,
        elementId: node.id,
        extractedData: node,
        transformationHistory: [],
        currentStatus: 'active'
      };

      this.records.set(record.id, record);
    });

    console.log(`初始化 ${this.records.size} 个Figma元素追踪记录`);
  }

  // 追踪Phase间转换
  private trackTransformation(fromPhase: number, toPhase: number, output: any): void {
    const transformationMap = this.analyzeTransformation(fromPhase, toPhase, output);

    transformationMap.forEach((transformation, elementId) => {
      const record = this.records.get(elementId);
      if (record) {
        const transformationStep: TransformationStep = {
          fromPhase,
          toPhase,
          transformation: transformation.type,
          dataLoss: transformation.dataLoss,
          timestamp: Date.now()
        };

        record.transformationHistory.push(transformationStep);
        record.currentStatus = transformation.status;

        if (transformation.dataLoss.lostFields.length > 0) {
          record.lossReason = transformation.dataLoss.reason;
          record.impactAssessment = this.assessImpact(transformation.dataLoss.lostFields);
        }
      }
    });
  }

  // 分析转换过程
  private analyzeTransformation(fromPhase: number, toPhase: number, output: any): Map<string, any> {
    const transformationMap = new Map();

    switch (toPhase) {
      case 2: // Phase1 → Phase2: Figma → Component
        this.analyzePhase1To2Transformation(output, transformationMap);
        break;
      case 3: // Phase2 → Phase3: Component → FieldNode
        this.analyzePhase2To3Transformation(output, transformationMap);
        break;
      case 4: // Phase3 → Phase4: FieldNode → Panels
        this.analyzePhase3To4Transformation(output, transformationMap);
        break;
    }

    return transformationMap;
  }

  // Phase1到Phase2转换分析
  private analyzePhase1To2Transformation(phase2Output: any, transformationMap: Map<string, any>): void {
    const { component, uiMapping, informationUsage } = phase2Output;

    // 分析哪些Figma元素被映射到React组件
    if (uiMapping && uiMapping.elementMappings) {
      uiMapping.elementMappings.forEach((mapping: any) => {
        transformationMap.set(mapping.figmaElementId, {
          type: 'ui_mapping',
          status: 'transformed',
          dataLoss: {
            lostFields: mapping.lostProperties || [],
            reason: mapping.simplificationReason || 'UI转换简化',
            approved: mapping.approved || false
          }
        });
      });
    }

    // 分析未使用的Figma元素
    if (informationUsage && informationUsage.unusedElements) {
      informationUsage.unusedElements.forEach((element: any) => {
        transformationMap.set(element.figmaElementId, {
          type: 'not_used',
          status: 'lost',
          dataLoss: {
            lostFields: ['entire_element'],
            reason: element.reason || '未知原因',
            approved: false
          }
        });
      });
    }
  }

  // Phase2到Phase3转换分析
  private analyzePhase2To3Transformation(phase3Output: any, transformationMap: Map<string, any>): void {
    const { fieldsConfig, editFields, panelMappings } = phase3Output;

    // 分析Props到FieldNode的转换
    Object.keys(fieldsConfig).forEach(propKey => {
      const fieldConfig = fieldsConfig[propKey];
      transformationMap.set(`prop_${propKey}`, {
        type: 'field_mapping',
        status: 'transformed',
        dataLoss: {
          lostFields: this.findLostPropsFields(propKey, fieldConfig),
          reason: '字段类型转换',
          approved: true
        }
      });
    });

    // 分析EditFields设计
    editFields.forEach((editField: any) => {
      transformationMap.set(`edit_${editField.key}`, {
        type: 'edit_field',
        status: 'active',
        dataLoss: {
          lostFields: [],
          reason: '',
          approved: true
        }
      });
    });
  }

  // Phase3到Phase4转换分析（如果有自定义面板）
  private analyzePhase3To4Transformation(phase4Output: any, transformationMap: Map<string, any>): void {
    const { customPanels } = phase4Output;

    if (customPanels) {
      customPanels.forEach((panel: any) => {
        transformationMap.set(`panel_${panel.name}`, {
          type: 'custom_panel',
          status: 'active',
          dataLoss: {
            lostFields: [],
            reason: '',
            approved: true
          }
        });
      });
    }
  }

  // 评估信息损失的影响程度
  private assessImpact(lostFields: string[]): 'low' | 'medium' | 'high' | 'critical' {
    if (lostFields.includes('entire_element')) return 'critical';

    const criticalFields = ['title', 'data', 'layout', 'interaction'];
    const importantFields = ['style', 'color', 'size', 'spacing'];

    const criticalLoss = lostFields.some(field =>
      criticalFields.some(critical => field.toLowerCase().includes(critical))
    );

    const importantLoss = lostFields.some(field =>
      importantFields.some(important => field.toLowerCase().includes(important))
    );

    if (criticalLoss) return 'critical';
    if (importantLoss) return 'high';
    if (lostFields.length > 5) return 'medium';
    return 'low';
  }

  // 查找Props字段转换中的损失
  private findLostPropsFields(propKey: string, fieldConfig: any): string[] {
    // 这里需要根据实际的字段转换逻辑来实现
    // 比较原始Props和FieldNode配置的差异
    return [];
  }

  // 获取信息损失报告
  getInformationLossReport(): InformationLossReport {
    const allRecords = Array.from(this.records.values());

    const lostElements = allRecords.filter(record => record.currentStatus === 'lost');
    const criticalLoss = lostElements.filter(record => record.impactAssessment === 'critical');
    const highImpactLoss = lostElements.filter(record => record.impactAssessment === 'high');

    return {
      totalElements: allRecords.length,
      preservedElements: allRecords.filter(record => record.currentStatus === 'active').length,
      transformedElements: allRecords.filter(record => record.currentStatus === 'transformed').length,
      lostElements: lostElements.length,
      criticalLoss: criticalLoss.length,
      highImpactLoss: highImpactLoss.length,
      detailedLoss: lostElements.map(record => ({
        elementId: record.elementId,
        elementType: record.elementType,
        lossReason: record.lossReason || 'Unknown',
        impact: record.impactAssessment || 'low',
        lostInPhase: this.findLossPhase(record)
      }))
    };
  }

  private findLossPhase(record: InformationTrackingRecord): number {
    const lossTransformation = record.transformationHistory.find(
      step => step.dataLoss.lostFields.includes('entire_element')
    );
    return lossTransformation?.toPhase || -1;
  }
}

// 反馈回路管理器
export class FeedbackLoopManager {
  private loops: FeedbackLoop[] = [];
  private fidelityTracker = new InformationFidelityTracker();

  constructor() {
    this.initializeFeedbackLoops();
  }

  private initializeFeedbackLoops(): void {
    // Phase5 → Phase2: UI还原度反馈
    this.loops.push({
      sourcePhase: 5,
      targetPhase: 2,
      feedbackType: 'validation',
      triggers: [
        {
          condition: 'uiRestorationRate < 0.95',
          threshold: 0.95,
          action: {
            type: 'rollback',
            instructions: 'UI还原度不足，需要回到Phase2重新生成组件，重点关注布局和样式映射',
            affectedPhases: [2, 3, 4, 5]
          }
        }
      ]
    });

    // Phase3 → Phase1: 字段覆盖度反馈
    this.loops.push({
      sourcePhase: 3,
      targetPhase: 1,
      feedbackType: 'validation',
      triggers: [
        {
          condition: 'fieldCoverageRate < 1.0',
          threshold: 1.0,
          action: {
            type: 'enhance',
            instructions: '字段覆盖不完整，需要检查Phase1的blueprint生成是否遗漏了重要配置项',
            affectedPhases: [1, 2, 3]
          }
        }
      ]
    });

    // Phase2 → Phase1: 信息损失反馈
    this.loops.push({
      sourcePhase: 2,
      targetPhase: 1,
      feedbackType: 'correction',
      triggers: [
        {
          condition: 'criticalInformationLoss > 0',
          threshold: 0,
          action: {
            type: 'alert',
            instructions: '检测到关键信息损失，需要验证Phase1的Figma数据提取是否完整',
            affectedPhases: [1, 2]
          }
        }
      ]
    });
  }

  // 处理Phase完成事件
  async handlePhaseCompletion(phase: number, output: any, qualityResult: any): Promise<FeedbackResult[]> {
    this.fidelityTracker.recordPhaseOutput(phase, output);

    const feedbackResults: FeedbackResult[] = [];

    // 检查所有相关的反馈循环
    const relevantLoops = this.loops.filter(loop => loop.sourcePhase === phase);

    for (const loop of relevantLoops) {
      for (const trigger of loop.triggers) {
        const shouldTrigger = await this.evaluateTriggerCondition(
          trigger.condition,
          qualityResult,
          this.fidelityTracker.getInformationLossReport()
        );

        if (shouldTrigger) {
          feedbackResults.push({
            loop,
            trigger,
            timestamp: Date.now(),
            severity: this.getSeverity(trigger.action.type),
            recommendation: trigger.action.instructions
          });
        }
      }
    }

    return feedbackResults;
  }

  // 评估触发条件
  private async evaluateTriggerCondition(
    condition: string,
    qualityResult: any,
    lossReport: InformationLossReport
  ): Promise<boolean> {
    try {
      // 构建评估上下文
      const context = {
        uiRestorationRate: this.getMetricScore(qualityResult, 'uiRestorationRate'),
        fieldCoverageRate: this.getMetricScore(qualityResult, 'fieldCoverageRate'),
        criticalInformationLoss: lossReport.criticalLoss,
        totalInformationLoss: lossReport.lostElements
      };

      // 简单的条件评估器
      return this.evaluateCondition(condition, context);
    } catch (error) {
      console.error('条件评估失败:', error);
      return false;
    }
  }

  private getMetricScore(qualityResult: any, metricName: string): number {
    const metric = qualityResult.metrics?.find((m: any) => m.name === metricName);
    return metric?.score || 0;
  }

  private evaluateCondition(condition: string, context: any): boolean {
    // 解析条件表达式（简化版）
    const conditionRegex = /(\w+)\s*([<>]=?)\s*([\d.]+)/;
    const match = condition.match(conditionRegex);

    if (!match) return false;

    const [, variable, operator, valueStr] = match;
    const value = parseFloat(valueStr);
    const contextValue = context[variable];

    if (contextValue === undefined) return false;

    switch (operator) {
      case '<': return contextValue < value;
      case '<=': return contextValue <= value;
      case '>': return contextValue > value;
      case '>=': return contextValue >= value;
      default: return false;
    }
  }

  private getSeverity(actionType: string): 'low' | 'medium' | 'high' | 'critical' {
    switch (actionType) {
      case 'rollback': return 'critical';
      case 'correct': return 'high';
      case 'enhance': return 'medium';
      case 'alert': return 'low';
      default: return 'medium';
    }
  }

  // 获取反馈循环状态
  getFeedbackLoopStatus(): FeedbackLoopStatus {
    return {
      totalLoops: this.loops.length,
      informationTrackingActive: true,
      lastUpdate: Date.now(),
      trackingRecords: this.fidelityTracker.getInformationLossReport()
    };
  }
}

// 类型定义
export interface InformationLossReport {
  totalElements: number;
  preservedElements: number;
  transformedElements: number;
  lostElements: number;
  criticalLoss: number;
  highImpactLoss: number;
  detailedLoss: {
    elementId: string;
    elementType: string;
    lossReason: string;
    impact: string;
    lostInPhase: number;
  }[];
}

export interface FeedbackResult {
  loop: FeedbackLoop;
  trigger: FeedbackTrigger;
  timestamp: number;
  severity: 'low' | 'medium' | 'high' | 'critical';
  recommendation: string;
}

export interface FeedbackLoopStatus {
  totalLoops: number;
  informationTrackingActive: boolean;
  lastUpdate: number;
  trackingRecords: InformationLossReport;
}

export const feedbackLoopManager = new FeedbackLoopManager();
